package com.quzi.kettle.socket;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.concurrent.atomic.AtomicBoolean;

import org.acra.sender.GoogleFormSender;

import android.os.Handler;
import android.util.Base64;
import android.util.Log;

import com.quzi.kettle.GlobalConfig;
import com.quzi.kettle.activitise.EasyLink;

public class UdpReceive extends Thread {
	private Handler handler = null;
	private boolean flag = false;
	public static DatagramSocket udpSocket;
	private static byte[] data = new byte[256];
	private static DatagramPacket udpPacket = new DatagramPacket(data, 256);

	public UdpReceive(Handler handler, boolean flag) {
		this.handler = handler;
		this.flag = flag;
	}

	private final AtomicBoolean started = new AtomicBoolean(false);

	@Override
	public synchronized void start() {
		if (!started.getAndSet(true)) {
			super.start();
		}
	}

	@Override
	public void run() {

		try {
			udpSocket = new DatagramSocket(9001);
		} catch (SocketException e) {
			System.out.println(e.toString());
		}

		while (flag) {
			try {
				udpSocket.receive(udpPacket);
			} catch (Exception e) {
				System.out.println(e.toString());
			}

			Log.d("qiwei", "haha");
			if (udpPacket.getLength() != 0) {
				Log.d("qiwei", "udpPacket.getLength() != 0");

				String codeString = new String(Base64.decode(
						udpPacket.getData(), 0), 0, Base64.decode(
						udpPacket.getData(), 0).length);
				Log.d("qiwei", "udp  = " + codeString);
				udpSocket.close();
				if (codeString.contains("success")) {
					if (GlobalConfig.topic.equals(codeString.replace("success",
							""))) {
						handler.obtainMessage(EasyLink.HAVEADD, "你已添加该水壶")
								.sendToTarget();
						Log.d("qiwei", "GlobalConfig.topic.equals");
						return;
					} else {
						GlobalConfig.topic = codeString.replace("success", "");
						Log.d("qiwei",
								"topic = " + codeString.replace("success", ""));
						handler.obtainMessage(EasyLink.BIND_DEVICE)
								.sendToTarget();
					}

				} else {
					Log.d("qiwei", "udp is not contain ");
				}

				flag = false;

			} else {
				Log.d("qiwei", "udpPacket.getLength() == 0");
			}
		}
	}

}
